<template>
  <div class="record-detail-container" v-if="!loading">
    <!-- 活动详情标题 -->
    <h2>签到详情</h2>

    <!-- 活动信息卡片 -->
    <el-card class="activity-card">
      <p v-if="activityType === '0'">
        普通签到，无更多内容。
      </p>
      <div v-if="activityType === '1'" class="gesture-display-wrapper">
        <GestureDisplay :gesturePoints="activityDetails.gesture" />
      </div>
      <p v-if="activityType === '2'">
        <PositionDisplay :locationData="activityDetails.locationDto"/>
      </p>
      <p v-if="activityType === '3'">
        <QRCode :value="activityDetails.qrcode" :size="360" :level="'H'"/>
      </p>
      <p v-if="activityType === '4'">
        签到码为：{{ activityDetails.code }}
      </p>
    </el-card>

    <!-- 学生签到情况 -->
    <el-card class="student-record-card">
      <h3>学生签到情况</h3>
      <StudentAttendance
          :aid="activityId"
          :recordPageSize="recordPageSize"
          @update:recordPage="handleRecordPageChange"
      />
    </el-card>
  </div>

  <!-- 加载状态 -->
  <div v-else class="loading-container">
    <el-skeleton :rows="5" animated />
  </div>
</template>

<script>
import { ElMessage, ElSkeleton } from 'element-plus';
import axios from 'axios';
import store from '@/store';
import StudentAttendance from './StudentAttendance.vue';
import GestureDisplay from './GestureDisplay.vue';
import PositionDisplay from "@/components/teacher/PositionDisplay.vue";
import QRCode from "qrcode.vue";

const api = axios.create({
  baseURL: store.getters.getBaseURL
});

// 请求和响应拦截器
api.interceptors.request.use(config => {
  const token = sessionStorage.getItem('userToken');
  if (token) {
    config.headers.Authorization = `Bearer ${token}`;
  }
  return config;
});

api.interceptors.response.use(
    response => response,
    error => {
      if (error.response?.status === 401) {
        window.location.href = '/loginAndRegister';
      }
      return Promise.reject(error);
    }
);

export default {
  components: {
    PositionDisplay,
    ElSkeleton,
    StudentAttendance,
    QRCode,
    GestureDisplay // 注册新组件
  },
  data() {
    return {
      loading: true, // 加载状态
      activityId: null,
      activityType: null,
      activityDetails: null,
      recordPageSize: 5,
      recordPage: 1,
      pollingInterval: null, // 轮询定时器
      pollingEnabled: true, // 轮询开关
    };
  },
  created() {
    // 从 URL 查询参数获取活动 ID 和类型
    this.activityId = this.$route.query.aid;
    this.activityType = this.$route.query.type;
    this.getActivityDetails();
  },
  methods: {
    // 获取活动详情
    getActivityDetails() {
      if (!this.activityId || !this.activityType) {
        ElMessage.error('缺少活动 ID 或类型');
        this.goBack();
        return;
      }

      api
          .get(`/activity/additionInfo/${this.activityId}/${this.activityType}`)
          .then(response => {
            if (response.data.status === 'success') {
              this.activityDetails = response.data.data;
              console.log('签到详情信息：', JSON.stringify(this.activityDetails));
            } else {
              ElMessage.error(response.data.info || '获取签到详情失败');
            }
          })
          .catch(error => {
            console.error('Error fetching activity details:', error);
            ElMessage.error('获取签到详情失败');
          })
          .finally(() => {
            this.loading = false;
          });
    },
    // 开始轮询
    startPolling() {
      if (this.activityType === '3') {
        this.pollingInterval = setInterval(() => {
          if (this.pollingEnabled) {
            this.getActivityDetails();
          }
        }, 3000);
      }
    },
    // 停止轮询
    stopPolling() {
      if (this.pollingInterval) {
        clearInterval(this.pollingInterval);
      }
    },
    // 处理分页变化
    handleRecordPageChange(page) {
      this.recordPage = page;
    },
    // 返回上一页
    goBack() {
      this.$router.go(-1);
    }
  },
  unmounted() {
    // 组件销毁时停止轮询
    this.stopPolling();
  },
  mounted() {
    // 组件挂载时开始轮询
    this.startPolling();
  }
};
</script>

<style scoped>
.record-detail-container {
  padding: 20px;
}

h2 {
  margin-bottom: 15px;
  color: #333;
  text-align: center;
}

h3 {
  margin-bottom: 15px;
  color: #333;
}

.activity-card {
  margin-bottom: 20px;
  padding: 20px;
}

.student-record-card {
  padding: 20px;
}

.el-card {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.loading-container {
  display: flex;
  justify-content: center;
  padding: 50px 0;
}

.gesture-display-wrapper {
  margin-bottom: 15px;
}

p {
  display: flex;
  justify-content: center;
  font-size: 1.6vw;
}
</style>